package com.example.service.impl;

import com.example.mapper.MachineMapper;
import com.example.pojo.Machine;
import com.example.pojo.PageResult;
import com.example.service.MachineService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MachineServiceImpl implements MachineService {

    @Autowired
    private MachineMapper machineMapper;

    public List<Machine> findAll() {
        return machineMapper.findAll();
    }

    @Override
    public PageResult page(Integer page, Integer pageSize){
        //设置分页参数
        PageHelper.startPage(page, pageSize);

        //执行查询
        List<Machine> list = machineMapper.findAll();
        Page<Machine> p = (Page<Machine>) list;

        //封装分页结果
        return new PageResult(p.getTotal(), p.getResult());
    }

    public void deleteById(Integer id) {
        machineMapper.deleteById(id);
        //重置自增主键
        //machineMapper.resetAutoIncrement();
        //将machineID大于指定值的记录的machineID减1
        ///machineMapper.decrementMachineIDAfter(machineID);
    }

    public void save(Machine machine) {
        //补全基础属性
        machine.setCreateTime(LocalDateTime.now());
        machine.setUpdateTime(LocalDateTime.now());
        machine.setIsConnected(0);
        //保存到数据库中
        machineMapper.insert(machine);
        //重置自增主键
        //machineMapper.resetAutoIncrement();
    }

    public Machine getById(Integer machineID) {
        return machineMapper.getById(machineID);
    }

    public void updata(Machine machine) {
        //补全基础属性
        machine.setUpdateTime(LocalDateTime.now());
        //保存到数据库中
        machineMapper.update(machine);
    }

    //获取所有设备isConnected
    public List<Machine> getAllIsConnected() {
        return machineMapper.getAllIsConnected();
    }


}
